package demo2;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-04
 * Time: 17:14
 */
//创建一个自己的线程池--固定线程个数为10
public class MtThreadPool {
    private BlockingQueue<Runnable> queue = new LinkedBlockingQueue<>();

    private void submit(Runnable runnable){
        try {
            queue.put(runnable);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public MtThreadPool(int nThreads){
        for(int i =0;i<nThreads;++i){
            Thread t = new Thread(()->{
                while(true){
                    try {
                        Runnable r = queue.take();
                        r.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        }
    }


    public static void main(String[] args) {
        //创建线程池对象
        MtThreadPool mtThreadPool = new MtThreadPool(10);
        //newFixedThreadPool---指可创建固定线程池数量
        //newCachedThreadPool---指可创建增容的线程池数量
        for(int i =0;i<100;++i){
            mtThreadPool.submit(new Runnable() {//submit-->用来存放任务并提交给线程池已有的线程执行
                @Override
                public void run() {
                    System.out.println("hello,world");
                }
            });
        }
    }
}
